package com.hjx.img;

import com.hjx.http.util.RequestUtil;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.zip.GZIPInputStream;

public class GetICBCImage {


    @Test
    public void getImg() throws Exception {
        String url = "https://epass.icbc.com.cn/servlet/ICBCVerificationCodeImageCreate?randomId=1546268583143655053&height=36&width=90&appendRandom=1546268583807";
        String fileFullPath = "imgs1/";
        for (int i = 0; i < 10; i++) {
            RequestUtil.getAsFile(fileFullPath + UUID.randomUUID().toString() + ".png", url, null, null);
        }

    }

    @Test
    public void recognize() throws IOException {
        doPostupload();
    }

    public static void doPostupload() throws IOException {
        HttpClient context = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://127.0.0.1:5000/b");
        post.setHeader("Accept-Language","zh-CN,zh;q=0.9");
//        post.setHeader("Accept-Encoding","gzip, deflate");  //像header这些自己去设置吧

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("name=\"File\"; filename=\"6de8.png\"", new File("C:\\Users\\woshi\\Desktop\\6de8.png"));//添加文件
        builder.addTextBody("Language", "9");  //添加文本类型参数
        post.setEntity(builder.build());
        HttpResponse response = context.execute(post);
        byte[] res =null;
        //获取参数
        /**请求发送成功，并得到响应**/
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//            res = EntityUtils.toByteArray(response.getEntity());
            System.out.println(EntityUtils.toString(response.getEntity()));
        }
//        System.out.println(Jsoup.parse(new String( uncompress(res),"utf-8")).select("div[class=div_res]"));

    }

    public static byte[] uncompress(byte[] b) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(b);
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }


}
